package com.ellecity06.common.helper

import android.media.MediaPlayer

/**
 * @author ellecity06
 * @time 2025/3/14 14:37
 * @des
 */
class AudioHelper(private val voicePlayListener: AudioPlayListener? = null) {
    private var mediaPlayer: MediaPlayer? = MediaPlayer()
    private var playingPath: String? = null
    private var isPlaying = false
    fun start(path: String) {
        if (isPlaying) {
            isPlaying = false
            pause()
        } else {
            isPlaying = true
            playVoice(path)
        }

    }

    fun pause() {
        voicePlayListener?.onAudioPause()
        mediaPlayer?.pause()
    }

    fun restartVoice() {
        isPlaying = true
        voicePlayListener?.onAudioReStart()
        mediaPlayer?.start()
    }


    fun stopAllVoice() {
        if (mediaPlayer != null) {
            if (mediaPlayer?.isPlaying != null && mediaPlayer?.isPlaying!!) {
                mediaPlayer?.stop()
            }
            mediaPlayer?.release()
            voicePlayListener?.onAudioStop()
            mediaPlayer = null
        }
        playingPath = null
    }

    private fun playVoice(path: String) {
        playingPath = path
        if (mediaPlayer == null) mediaPlayer = MediaPlayer()

        if (path.startsWith("http:") || path.startsWith("https:")) {
            playHttpVoice(path)
        } else {
            playFileVoice(path)
        }
    }

    private fun playHttpVoice(path: String) {
        mediaPlayer?.reset()
        mediaPlayer?.setDataSource(path)
        mediaPlayer?.setOnPreparedListener {
            voicePlayListener?.onAudioStart()
            mediaPlayer?.start()
        }
        mediaPlayer?.setOnCompletionListener {
            stopAllVoice()
        }
        mediaPlayer?.prepareAsync()


    }

    private fun playFileVoice(path: String) {
        if (mediaPlayer != null) {
            mediaPlayer?.reset()
            voicePlayListener?.onAudioStart()
            mediaPlayer?.setDataSource(path)
            mediaPlayer?.prepare()
            mediaPlayer?.start()
            mediaPlayer?.setOnCompletionListener {
                stopAllVoice()
            }
        }
    }


    interface AudioPlayListener {
        fun onAudioStart()
        fun onAudioPause()
        fun onAudioReStart()
        fun onAudioStop()
    }
}